package bb.lanxing.net.utils;

import java.io.File;
import java.util.Map;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public final class OkHttpUtils {
    public static Headers buildHeaders(Headers originHeaders, Map<String, String> headers) {
        if (originHeaders == null && headers == null) {
            return null;
        }
        if (headers == null) {
            return originHeaders;
        }
        Headers.Builder newBuilder = originHeaders != null ? originHeaders.newBuilder() : new Headers.Builder();
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            newBuilder.add(entry.getKey(), entry.getValue());
        }
        return newBuilder.build();
    }

    public static MultipartBody buildMultipartBody(Map<String, Object> pairs, MediaType mediaType) {
        if (pairs == null || pairs.isEmpty()) {
            return null;
        }
        MultipartBody.Builder type = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (Map.Entry<String, Object> entry : pairs.entrySet()) {
            if (entry != null && entry.getValue() != null) {
                if (entry.getValue() instanceof File) {
                    File file = (File) entry.getValue();
                    type.addFormDataPart(entry.getKey(), file.getName(), RequestBody.create(mediaType, file));
                } else {
                    type.addFormDataPart(entry.getKey(), entry.getValue().toString());
                }
            }
        }
        return type.build();
    }
}
